package com.jspgou.cms.action.member;

import static com.jspgou.cms.Constants.PROCESS_URL;
import static com.jspgou.cms.Constants.MEMBER_SYS;
import static com.jspgou.cms.Constants.TPLDIR_INDEX;
import static com.jspgou.core.web.Constants.MESSAGE;
import static com.jspgou.core.web.Constants.RETURN_URL;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.jspgou.cms.entity.ShopMember;
import com.jspgou.cms.service.LoginSvc;
import com.jspgou.cms.web.ShopFrontHelper;
import com.jspgou.cms.web.SiteUtils;
import com.jspgou.common.security.BadCredentialsException;
import com.jspgou.common.security.UserNotAcitveException;
import com.jspgou.common.security.UsernameNotFoundException;
import com.jspgou.common.web.RequestUtils;
import com.jspgou.common.web.springmvc.MessageResolver;
import com.jspgou.core.entity.Website;
import com.jspgou.core.security.UserNotInWebsiteException;
import com.jspgou.core.web.WebErrors;

@Controller
public class LoginAct {
	private static final Logger log = LoggerFactory.getLogger(LoginAct.class);
	
	private static final String LOGIN_INPUT = "tpl.loginInput";
	
	public static final String TPL_INDEX = "tpl.index";
	
	@RequestMapping(value = "/login.jspx", method = RequestMethod.GET)
	public String loginInput(HttpServletRequest request, ModelMap model) {
		Website web = SiteUtils.getWeb(request);
		String processUrl = RequestUtils.getQueryParam(request, PROCESS_URL);
		String returnUrl = RequestUtils.getQueryParam(request, RETURN_URL);
		String message = RequestUtils.getQueryParam(request, MESSAGE);
		ShopFrontHelper.setCommonData(request, model, web);
		if (!StringUtils.isBlank(processUrl)) {
			model.addAttribute(PROCESS_URL, processUrl);
		}
		if (!StringUtils.isBlank(returnUrl)) {
			model.addAttribute(RETURN_URL, returnUrl);
		}
		if (!StringUtils.isBlank(message)) {
			model.addAttribute(MESSAGE, message);
		}
		return web.getTplSys(MEMBER_SYS, MessageResolver.getMessage(request,LOGIN_INPUT), request);
	}

	@RequestMapping(value = "/login.jspx", method = RequestMethod.POST)
	public String loginSubmit(String username, String password,
			String processUrl,String returnUrl, String message,
			HttpServletRequest request,HttpServletResponse response,
			ModelMap model) {
		Website web = SiteUtils.getWeb(request);
		WebErrors errors = WebErrors.create(request);
		ShopMember member;
		try {
			member = loginSvc.memberLogin(request, response, web, username,password);
			log.info("member '{}' login success.", username);
			String view = getView(processUrl, returnUrl);
			if (view != null) {
				if(member.getIsEmployee()){
					return "redirect:store/index.jspx";
				}else{
				 return view;
				}
			} else {
				model.addAttribute("member", member);
				ShopFrontHelper.setCommonData(request, model, web);
				//登录成功跳转到首页
				return web.getTemplate(TPLDIR_INDEX, MessageResolver.getMessage(request,TPL_INDEX), request);
			}
		} catch (UsernameNotFoundException e) {
			errors.addErrorCode("error.usernameNotExist");
		} catch (BadCredentialsException e) {
			errors.addErrorCode("error.passwordInvalid");
		} catch (UserNotInWebsiteException e) {
			errors.addErrorCode("error.usernameNotInWebsite");
		}catch(UserNotAcitveException e){
			errors.addErrorCode("error.usernameNotActivated");
		}	
		errors.toModel(model);
		ShopFrontHelper.setCommonData(request, model, web);
		return web.getTplSys(MEMBER_SYS, MessageResolver.getMessage(request,LOGIN_INPUT), request);
	}

	@RequestMapping("/logout.jspx")
	public String logout(String redirectUrl, HttpServletRequest request,
			HttpServletResponse response) {
		loginSvc.logout(request, response);
		if (!StringUtils.isBlank(redirectUrl)) {
			return "redirect:" + redirectUrl;
		} else {
			return "redirect:/";
		}
	}
	
	/**
	 * 获得地址
	 * 
	 * @param processUrl
	 * @param returnUrl
	 * @param authId
	 * @param defaultUrl
	 * @return
	 */
	private String getView(String processUrl, String returnUrl) {
		if (!StringUtils.isBlank(processUrl)) {
			StringBuilder sb = new StringBuilder("redirect:");
			sb.append(processUrl);
			if (!StringUtils.isBlank(returnUrl)) {
				sb.append("?").append(RETURN_URL).append("=").append(returnUrl);
			}
			return sb.toString();
		} else if (!StringUtils.isBlank(returnUrl)) {
			StringBuilder sb = new StringBuilder("redirect:");
			sb.append(returnUrl);
			return sb.toString();
		} else {
			return null;
		}
	}

	@Autowired
	private LoginSvc loginSvc;
}
